# coding:utf-8
import os
import logging
import datetime

# 根据指定字符串截取并重命名
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
strftime = datetime.datetime.now().strftime('%Y-%m-%d')


def replace_file_name(path, list=['WeChat_', '微信图片_']):
    for root_dir, dirs, files in os.walk(path):
        for file in files:
            old_name = file
            for item in list:
                old_file = os.path.join(root_dir, old_name)
                new_name = str(file).replace(item, '')
                new_file = os.path.join(root_dir, new_name)
                # 判断是否存在
                is_remove = False
                i = 0
                while os.path.exists(new_file) and i != 0:
                    logger.info(new_name + "已存在！处理中。。。")
                    # 判断文件是否相同 如果相同则删除，并保存删除记录
                    if os.path.getsize(new_file) == os.path.getsize(old_file):
                        file_name = '%s-%s.txt' % ('已删除重复文件', strftime)
                        with open(file_name, 'a+', encoding='utf-8') as f:
                            f.write(old_file + '\n')
                        # os.remove(old_file)
                        is_remove = True
                    else:
                        filename, file_type = os.path.splitext(new_name)
                        new_name = filename + '_' + str(i) + file_type
                        new_file = os.path.join(root_dir, new_name)
                        i += 1
                        is_remove = False
                if not is_remove and new_name != old_name:
                    os.rename(old_file, os.path.join(root_dir, new_name))
                    old_name = new_name


if __name__ == '__main__':
    # 用户路径
    user_dir = os.path.expanduser('~') + os.sep
    print(user_dir)
    # filePath = user_dir + "Videos"
    filePath = user_dir + "Downloads" + os.sep
    # filePath = user_dir + "Pictures" + os.sep + 'Camera Roll' + os.sep
    replace_file_name(filePath, ['WeChat_', '微信图片_'])
    # C:\Users\Augurit\Pictures\Camera Roll
